package com.training.servlet;

import com.training.action.Action;
import com.training.bean.MvcBean;
import com.training.form.ActionForm;
import com.training.form.FormBeanRef;
import com.training.parser.XMLParser;
import org.jdom.JDOMException;
import org.omg.CORBA.Request;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Ywen on 2018/12/2.
 */
public class ActionServlet extends HttpServlet {

    //private static Map<String, MvcBean> mvcBeanMap = new HashMap();
    //
    //static {
    //    try {
    //        mvcBeanMap = XMLParser.load("");
    //    } catch (JDOMException e) {
    //        e.printStackTrace();
    //    } catch (IOException e) {
    //        e.printStackTrace();
    //    }
    //}


    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();
        Map<String, MvcBean> mvcBeanMap = (Map<String, MvcBean>) req.getServletContext().getAttribute("mvcConfig");
        MvcBean mvcBean = mvcBeanMap.get(servletPath);
        String formBeanType = mvcBean.getFormBeanType();
        ActionForm actionForm = FormBeanRef.load(formBeanType, req);
        String actionType = mvcBean.getActionType();
        Action action;
        String url = "";
        try {
            Class aClass = Class.forName(actionType);
            action = (Action) aClass.newInstance();
            url = action.execute(actionForm, mvcBean.getActionForwadMap(), req, resp);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        RequestDispatcher dispatcher = req.getRequestDispatcher(url);
        dispatcher.forward(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

}
